﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Commerce.Common;
using Commerce.PayPal;
using umbraco.cms.businesslogic.media;

namespace CommerceForUmbraco.usercontrols
{
    public static class CartEvent
    {
        public delegate void AddToCartHandler(int productID, int quantity);
        public static event AddToCartHandler AddToCart;

        public static void Add(int productID, int quantity)
        {
            if(AddToCart != null)
               AddToCart(productID,quantity);
        }

    }


    public partial class MiniCart : System.Web.UI.UserControl
    {
        // currentOrder object
        protected Order currentOrder;
        protected decimal orderSubTotal = 0;

        public void UpdateCart()
        {
            pnlAdded.Visible = false;

            OrderItemCollection orderItemCollection = OrderController.GetCartItems();
            if (orderItemCollection.Count == 0)
            {

                pnlEmtpy.Visible = true;
                pnlFull.Visible = false;
            }
            else
            {
                pnlEmtpy.Visible = false;
                pnlFull.Visible = true;

                try
                {
                    rptBasket.DataSource = orderItemCollection;
                    rptBasket.DataBind();

                    decimal dTotal = 0;
                    foreach (OrderItem item in orderItemCollection)
                    {
                      
                        dTotal += item.LineTotal;
                    }

                    orderSubTotal = dTotal;

                    UpdateCrossSell(orderItemCollection[orderItemCollection.Count - 1].ProductID);

                }
                catch
                {
                    // set safe display
                }
            }
        }

        public void UpdateCrossSell(int relatedProductID)
        {
            rptCrossSell.Visible = true;

            if (relatedProductID != 0)
            {
                Commerce.Common.ProductCrossSellCollection crossSell = new ProductCrossSellCollection();
                crossSell.Where("fromProductID", relatedProductID);
                crossSell.Load();

                DataTable crossSellTable = crossSell.ToDataTable();

                foreach (DataRow dr in crossSellTable.Rows)
                {
                    int mediaId = int.Parse(dr["DefaultImage"].ToString());
                    dr["DefaultImage"] = new Media(mediaId).getProperty("umbracoFile").Value.ToString();
                }

                rptCrossSell.DataSource = crossSellTable;
                rptCrossSell.DataBind();

                if (crossSell.Count == 0)
                {
                    rptCrossSell.Visible = false;
                }

            }
            else
            {
                rptCrossSell.Visible = false;
            }
        }

        public void UpdateAdded()
        {
            pnlAdded.Visible = true;
            pnlEmtpy.Visible = false;
            pnlFull.Visible = false;

            Product addedProduct = new Product(LatestProduct);
            lblAddedProductName.Text = addedProduct.ProductName;
            lblAddedProductPrice.Text = addedProduct.OurPrice.ToString("C");
            lblAddedProductQuantity.Text = LatestProductQuantity.ToString();

            imgAddedProductImage.Src = new Media(int.Parse(addedProduct.DefaultImage.ToString())).getProperty("umbracoFile").Value.ToString();
            imgAddedProductImage.Alt = addedProduct.ProductName;

            OrderItemCollection orderItemCollection = OrderController.GetCartItems();

            try
            {
                rptOtherItems.DataSource = orderItemCollection;
                rptOtherItems.DataBind();

                decimal dTotal = 0;
                foreach (OrderItem item in orderItemCollection)
                {
                    dTotal += item.LineTotal;
                }

                orderSubTotal = dTotal;

            }
            catch
            {
                // set safe display
            }

            UpdateCrossSell(addedProduct.ProductID);
            LatestProduct = 0;
        }

        private int LatestProduct
        {
         
            get
            {
                if (ViewState["LatestProduct"] != null)
                    return Convert.ToInt32(ViewState["LatestProduct"]);
                else
                    return 0;
            }
            set
            {
                ViewState["LatestProduct"] = value;
            }
        }

        private int LatestProductQuantity
        {

            get
            {
                if (ViewState["LatestProductQuantity"] != null)
                    return Convert.ToInt32(ViewState["LatestProductQuantity"]);
                else
                    return 0;
            }
            set
            {
                ViewState["LatestProductQuantity"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CartEvent.AddToCart += new CartEvent.AddToCartHandler(Testing_AddToCart);

            if (!IsPostBack)
                UpdateCart();
            else
                if (LatestProduct != 0)
                {
                    UpdateAdded();
                }
        }

        void Testing_AddToCart(int productID, int quantity)
        {
            LatestProduct = productID;
            LatestProductQuantity = quantity;
           
            UpdateAdded();
        }

        public void Basket_ItemCommand(Object sender, RepeaterCommandEventArgs e)
        {
            string action = ((ImageButton)e.CommandSource).CommandArgument;

            switch (action)
            {
                case "remove":
                    DeleteItem(sender, e);
                    break;
                case "update":
                    UpdateItem(sender, e);
                    break;
            }
        }

        protected void UpdateItem(Object sender, RepeaterCommandEventArgs e)
        {
            Label lblProductID = (Label)e.Item.FindControl("lblProductID");
            TextBox newQuantity = (TextBox)e.Item.FindControl("qtyEntry");
            int orderID = OrderController.GetCartOrderID();

            if (lblProductID != null && newQuantity != null)
            {
                OrderController.AdjustQuantity(orderID, int.Parse(lblProductID.Text), "", int.Parse(newQuantity.Text));
            }

            UpdateCart();
        }

        protected void DeleteItem(Object sender, RepeaterCommandEventArgs e)
        {
            Label lblProductID = (Label)e.Item.FindControl("lblProductID");

            if (lblProductID != null)
            {
                OrderController.RemoveItem(int.Parse(lblProductID.Text));
            }

            UpdateCart();
        }

        protected void btnCart_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utility.GetCartUrl(), true);
        }

        protected void btnCheckout_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utility.GetCheckoutUrl(), true);
            
        }

        protected void btnPPExpressCheckout_Click(object sender, ImageClickEventArgs e)
        {
            PayPalCheckOut();
        }

        protected void btnPPExpressCheckout2_Click(object sender, EventArgs e)
        {
            PayPalCheckOut();
        }

        protected void PayPalCheckOut()
        {
            try
            {
                // set order information
                SetCurrentOrder();
                SetOrderInfo();

                // redirect to PayPal
                SetExpressCheckout();

            }
            catch (Exception ex)
            {
                //emptyMessage.Visible = true;
                //emptyMessage.Text = "We're sorry, an error occured.<br />" + ex.Message;
            }
        }

        protected void SetExpressCheckout()
        {
            try
            {
                // SetExpressCheckout
                APIWrapper wrapper = GetPPWrapper();

                string successURL = Utility.GetPayPalExpressCheckoutSuccessUrl();
                string failURL = Utility.GetPayPalExpressCheckoutFailUrl();
                string sUrl = "";

                if (currentOrder.Items.Count > 0)
                {
                    string ppToken = wrapper.SetExpressCheckout(string.Empty, currentOrder.CalculateSubTotal(),
                     successURL, failURL, false, new Address());
                    if (ppToken.ToLower().Contains("error"))
                    {
                        throw new Exception("PayPal has returned an error message: " + ppToken.ToString());
                    }
                    else
                    {

                        sUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;

                        if (!SiteConfig.APIIsLive)
                        {
                            sUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;
                        }

                        try
                        {
                            Response.Redirect(sUrl, false);
                        }
                        catch (Exception)
                        {
                            // ResultMessage1.ShowFail(x.Message);
                            throw;
                        }
                    }

                }
                else
                {
                    // send back to the cart page
                    Response.Redirect(Utility.GetCartUrl(), false);
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void SetOrderInfo()
        {
            currentOrder.ShippingAddress = null;
            currentOrder.BillingAddress = null;
        }

        protected void SetCurrentOrder()
        {
            if (currentOrder == null)
                currentOrder = OrderController.GetCurrentOrder();
        }

        protected APIWrapper GetPPWrapper()
        {
            SiteConfig.Load();

            APIWrapper wrapper =
              new APIWrapper(SiteConfig.PayPalAPIAccountName
                    , SiteConfig.PayPalAPIAccountPassword
                    , SiteConfig.APIsignature
                    , (CurrencyCode)Enum.Parse(typeof(CurrencyCode), SiteConfig.defaultCurrencyCode)
                    , SiteConfig.APIIsLive);

            return wrapper;
        }

        protected void btnCCCheckout_Click(object sender, ImageClickEventArgs e)
        {
            // get checkout link from config
            Response.Redirect(Utility.GetCheckoutUrl(), true);
        }

        protected void btnCCCheckout2_Click(object sender, EventArgs e)
        {
            // get checkout link from config
            Response.Redirect(Utility.GetCheckoutUrl(), true);
        }

        protected void btnAddToCart_Click(object sender, EventArgs e)
        {           

            Commerce.Common.Product prod = new Commerce.Common.Product(int.Parse(((LinkButton)sender).CommandArgument));
            prod.Quantity = 1;
            OrderController.AddItem(prod);

            this.LatestProduct = prod.ProductID;
            this.LatestProductQuantity = 1;
            UpdateAdded();
            // send to cart page
            //Response.Redirect(Utility.GetCartUrl(), true);


        }

        public string GetProductLink(string productID)
        {
            Product thisProduct = new Product(int.Parse(productID));
            return Utility.GetRewriterUrl("product", thisProduct.UrlFriendly, "");
            
        }

       
    }
}